package cn.fl.capital.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.comm.facade.upload.constant.UploadConstant;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.capital.condition.InsFileSyncDQC;
import cn.fl.capital.condition.InsFileSyncQC;
import cn.fl.capital.service.IInsFileSyncService;
import cn.fl.capital.vo.InsFileSyncVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.api.ISysSequenceApiService;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.fl.system.vo.SysUlFilesRecVO;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author huangkailun
 * @Date 15:32 2020-01-02
 * @Description 资方用传文件的方式与我司同步数据，一条记录代表一个文件。 控制层
 */
@Controller
@RequestMapping("/capital/insFileSync")
public class InsFileSyncController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(InsFileSyncController.class);

    /**
     * InsFileSync 服务层BEAN
     */
    @Autowired
    private IInsFileSyncService insFileSyncService;

    @Autowired
    private ISysUlFilesRecService sysUlFilesRecService;

    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    @Autowired
    private ISysSequenceApiService sysSequenceApiService;

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        List<SysDictionaryDTO> dictionaryDTOS = this.sysDictionaryApiService.searchGroup("11000", "0000", "INS0074");
        List<KeyValueVO> insCdNms = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(dictionaryDTOS)) {
            for (SysDictionaryDTO dic : dictionaryDTOS) {
                if ("jxbank".equals(dic.getCode()) || "qdghbank".equals(dic.getCode())) {
                    KeyValueVO vo = new KeyValueVO();
                    vo.setKey(dic.getCode());
                    vo.setValue(dic.getCodeNm());
                    insCdNms.add(vo);
                }
            }
        }
        ModelAndView view = new ModelAndView("capital/insFileSync/listFilePage");
        view.addObject("insCdNms", insCdNms);
        return view;
    }

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/showInsFileSyncD.do", method = {RequestMethod.GET})
    public ModelAndView showInsFileSyncD(HttpServletRequest request, HttpServletResponse response) {
        // 文件上传主表id
        String id = request.getParameter("id");
        ModelAndView view = new ModelAndView("capital/insFileSync/listInsFileDPage");
        view.addObject("id", id);
        return view;
    }

    /**
     * 新增文件上传主表INS_FILE_SYNC数据并新增文件上传记录
     */
    @RequestMapping(value = "/uploadFile.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object uploadFile(HttpServletRequest request) throws BaseException {
        DataResultDTO result = new DataResultDTO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        // 文件参数
        String fileParams = request.getParameter("fileParams");
        String insNm = request.getParameter("insNm");
        if(StringUtils.isEmpty(insNm)){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("请选择要上传的资方是哪个");
            return result;
        }
        if (StringUtils.isEmpty(fileParams)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("解析文件错误，上传文件为空！");
            BaseLogUtils.info(logger, "uploadFile", "资方代后上传解析文件路径为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        try {
            JSONArray jsonArray = JSONArray.parseArray(fileParams);
            JSONObject object = (JSONObject)jsonArray.get(0);
            String fileNm = object.getString("fileNm");
            if (StringUtils.isNotEmpty(fileNm)) {
                if (!fileNm.endsWith(".xls") && !fileNm.endsWith(".XLS") && !fileNm.endsWith(".xlsx") && !fileNm.endsWith(".XLSX")) {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("请上传xls或xlsx文件");
                    return result;
                }
            }
            // 提前获取上传文件的id
            Long id = sysSequenceApiService.getFun("FN_GEN_INS_FILE_SYNC_ID");
            result = this.insFileSyncService.uploadAttachment(fileParams, result, id);
            if (BaseConstant.IS_YESNO_YES == result.getSuccess()) {
                InsFileSyncVO vo = new InsFileSyncVO();
                vo.setId(id);
                vo.setInsCd(insNm);
                vo.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
                vo.setCrtNm(CurrentThreadContext.getCurrentUserName());
                result = this.insFileSyncService.parseExcel(vo);
            } else {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("文件上传失败，请重新上传！");
            }
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.newLogger("江西银行贷后文件上传失败").setThrowable(ex).info();
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.newLogger("江西银行贷后文件上传失败").setThrowable(ex).info();
        }
        return result;
    }

    /**
     * 下载江西银行贷后数据文件
     */
    @RequestMapping(value = "/downloadFile.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object downloadFile(HttpServletRequest request, HttpServletResponse response) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_FILE_DOWNLOAD_SUCC);
        // 文件ID
        String fileId = request.getParameter("fileId");
        String rootPath = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_ROOT_PATH);
        String serverPath = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_SERVER_PATH);
        try {
            if (StringUtils.isNotBlank(fileId)) {
                SysUlFilesRecVO file = this.sysUlFilesRecService.selectById(Long.valueOf(fileId));
                if (null != file) {
                    String fileName = file.getFileNm();
                    response.setCharacterEncoding("UTF-8");
                    response.setDateHeader("Expires", 0);
                    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
                    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
                    response.setHeader("Pragma", "no-cache");
                    if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                        fileName = URLEncoder.encode(fileName, "UTF-8");
                    } else {
                        fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
                    }
                    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                    ServletOutputStream out = response.getOutputStream();
                    // 读取要下载的文件，保存到文件输入流
                    String filePath = file.getFilePath();
                    if (StringUtils.isNotEmpty(filePath)) {
                        filePath = filePath.replace(serverPath, "");
                        filePath = rootPath + filePath;
                    }
                    File outFile = new File(filePath);
                    InputStream in = new FileInputStream(outFile);
                    // 创建输出流
                    // 创建缓冲区
                    byte buffer[] = new byte[1024];
                    int len = 0;
                    // 循环将输入流中的内容读取到缓冲区当中
                    while ((len = in.read(buffer)) > 0) {
                        // 输出缓冲区的内容到浏览器，实现文件下载
                        out.write(buffer, 0, len);
                    }
                    // 关闭文件输入流
                    in.close();
                    // 关闭输出流
                    out.close();
                } else {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("未找到要下载的文件！");
                    return result;
                }
            }
            BaseLogUtils.newLogger("下载江西银行贷后文件成功").setKeys("fileId:" + fileId).info();
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("文件下载失败！");
            BaseLogUtils.newLogger("下载江西银行贷后文件失败").setThrowable(ex).setKeys("fileId:" + fileId).info();
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("文件下载失败！");
            BaseLogUtils.newLogger("下载江西银行贷后文件失败").setThrowable(ex).setKeys("fileId:" + fileId).info();
        }
        return result;
    }

    /**
     * 初始化贷后上传数据明细列表
     */
    @RequestMapping(value = "/initInsFileDList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initInsFileDList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        // 上传文件主表id
        String id = request.getParameter("id");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }
        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        InsFileSyncDQC qc = new InsFileSyncDQC();
        if (StringUtils.isNotEmpty(id)) {
            qc.setPid(Long.valueOf(id));
        }
        page.setCondition(qc);
        Pager pager = this.insFileSyncService.searchFileDListPage(page);
        List<InsFileSyncVO> list = (List<InsFileSyncVO>) pager.getResultList();
        ListPageVO<InsFileSyncVO> listPage = new ListPageVO<InsFileSyncVO>(list, pager.getTotalCount());
        return listPage;
    }

    /**
     * 贷后上传数据主列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        // 机构名称
        String insNm = request.getParameter("insNm");
        // 数据日期
        String dataDate = request.getParameter("dataDate");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }
        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        InsFileSyncQC qc = new InsFileSyncQC();
        if (StringUtils.isNotEmpty(insNm)) {
            qc.setInsCd(insNm);
        }
        if (StringUtils.isNotEmpty(dataDate)) {
            qc.setDataDate(DateUtils.formatStringToDate(dataDate, DateUtils.YYYY_MM_DD));
        }
        page.setCondition(qc);
        Pager pager = this.insFileSyncService.searchListPage(page);
        List<InsFileSyncVO> list = (List<InsFileSyncVO>) pager.getResultList();
        ListPageVO<InsFileSyncVO> listPage = new ListPageVO<InsFileSyncVO>(list, pager.getTotalCount());
        return listPage;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            return result;
        }

        try {
            InsFileSyncVO vo = this.insFileSyncService.selectById(Long.valueOf(id));
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
            }
            result.setData(vo);
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
        }
        return result;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String name = request.getParameter("name");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        InsFileSyncVO entity = null;
        try {
            entity = new InsFileSyncVO();
            //TODO ADD PARAM
            Long id = this.insFileSyncService.add(entity);
            result.setData(id);
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
        }

        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            return result;
        }
        InsFileSyncVO entity = null;
        try {
            entity = new InsFileSyncVO();
            entity.setId(Long.valueOf(id));
            //entity.setName(name);
            //TODO ADD PARAM
            boolean success = this.insFileSyncService.modify(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            }
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
        }
        return result;
    }

}

